package ttestExecuter;

import java.util.concurrent.TimeUnit;

import station.DataMessage;

public class SlotExecuter implements Runnable {

    // normally not here!
    TestSlot[] slots = new TestSlot[20];
    private boolean isRunning = true;
    private byte nextSlot = 0;
    private static SlotExecuter sExecInstance = new SlotExecuter();

    public static SlotExecuter getInstance() {
        return sExecInstance;
    }

    /*
     * Wegen umstrukturierung von DataMessage geschlossen....
     */
    // public SlotExecuter() {
    // for (byte i = 0; i < slots.length; i++) {
    // slots[i] = new TestSlot(new DataMessage(new byte[] {i}, i));
    // }
    // }

    @Override
    public void run() {
        CostumScheduledExecuter cse = new CostumScheduledExecuter(10,
                new CostumThreadFactory());
        System.out.println("START!");

        long standardDelay = 50;
        long syncTuning = 0; // sync difference goes here!

        System.out.println("Start Threads!");
        cse.scheduleWithFixedDelay(new TestSender(), 25, standardDelay,
                TimeUnit.MILLISECONDS);
        while (isRunning) {
            if (cse.getTaskCount() == 20L) {
                cse.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
                cse.shutdown();
                isRunning = false;
            }
        }
        syncTuning = syncTime();
        standardDelay -= syncTuning;
    }

    private long syncTime() {
        return 0;
    }

    public DataMessage nextMsg() {
        DataMessage dataMsg = slots[nextSlot++].getMessage();
        // dataMsg.setNextSlot(nextSlot);
        return dataMsg;
    }

}
